package com.qfedu.service.impl;

import com.qfedu.dao.UserDao;
import com.qfedu.dao.impl.UserDaoImpl;
import com.qfedu.entity.User;
import com.qfedu.service.UserService;
import com.qfedu.utils.*;

import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public User findUserByUserName(String username) throws SQLException {
        return userDao.findUserByUserName(username);
    }

    @Override
    public boolean registerUser(User user) throws SQLException {
        user.setUpassword(MD5Utils.md5(user.getUpassword()));
        user.setUrole(Constants.ROLE_CUSTOMER);
        user.setUstatus(Constants.USER_NOT_ACTIVE);
        user.setCode(RandomUtils.createActive());
        EmailUtils.sendEmail(user);
        int num = userDao.insertUser(user);
        if(num > 0){
            return true;
        }
        return false;
    }

    @Override
    public boolean activeUserByCode(String code) throws SQLException {
        String realCode = Base64Utils.decode(code);
        int num = userDao.updateUserStatusByCode(Constants.USER_ACTIVE, realCode);
        if (num > 0){
            return true;
        }
        return false;
    }
}
